package com.computec.service.command;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;

import com.computec.encolador.source.EncoladorSource;

public class CommandService {
	EncoladorSource source;
	List commandList;
	private static Logger log = Logger.getLogger(org.apache.axis2.transport.SimpleAxis2Server.class);
	public CommandService(){
		source=new EncoladorSource();
		String os=System.getProperty("os.name");
		String[] arrayOs_=os.split(" ");
		
		System.out.println("Sistema:"+os);
		String commands="";
		boolean osWindows=false;
		for(int i=0;i<arrayOs_.length;i++){		
			boolean current_=arrayOs_[i].equalsIgnoreCase("Windows");
			osWindows=(osWindows || current_);
		}
		
		if(osWindows){
			commands=source.getEncoladorSetupKey("commands");	
		}else{
			commands=commands.toUpperCase();
			commands=source.getEncoladorSetupKey("commandsLinux");	
		}		
		String[] commandsArray=commands.split(",");
		this.commandList=Arrays.asList(commandsArray);
	}
	
	public boolean runCommand(String command){
		boolean ret_=false;		
		String[] array_=command.split(" ");
		boolean badCommand=false;
		for(int i=0;i<array_.length;i++){						
			badCommand=(badCommand || commandList.contains(array_[i].toUpperCase()));
		}
		if(!badCommand){	
			log.info("Comando ejecutado:"+command);
			try {
		      String line;
		      Process p1 = Runtime.getRuntime().exec
		        (command);		      
		      BufferedReader input =
		        new BufferedReader
		          (new InputStreamReader(p1.getInputStream()));
		      while ((line = input.readLine()) != null) {
		        log.info(line);
		      }
		      input.close();
		      ret_=true;
		    }
		    catch (Exception err) {
		      err.printStackTrace();
		    }
		}else{
			log.error("Comando no ejecutado:"+command);
		}
		    return ret_;
	}
		
}

